package com.jzo2o.market.config;

import com.jzo2o.redis.properties.RedisSyncProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfiguration {

    //定义线程池
    @Bean("syncThreadPool")
    public ThreadPoolExecutor synchronizeThreadPool(RedisSyncProperties redisSyncProperties){
        //同步队列的个数，默认10
        int queueNum = redisSyncProperties.getQueueNum();
        //核心线程数
        int corePoolSize = 1;
        //最大线程数，因为我们有10个队列，每个队列由一个线程去处理
        int maximumPoolSize = queueNum;
        //空闲时间
        long keepAliveTime = 120;
        TimeUnit unit = TimeUnit.SECONDS;
        //阻塞队列，该线程当时在忙，如果来执行同步任务，此时不会去在队列存储该任务，使用synchronousQueue
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(queueNum);
        //拒绝策略
        //指定拒绝策略未discardPolicy
        RejectedExecutionHandler rejectionHandler = new ThreadPoolExecutor.DiscardPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, rejectionHandler);
        return threadPoolExecutor;
    }
}
